/**
 * @file malloc.c
 * @author sqqdfny@163.com 
 * @brief For the adaptation of newlib, 
 *        if your target system is based on the implementation of newlib, 
 *        this file enables you to call the 
 *             malloc()/calloc()/realloc()/free() 
 *             functions provided by newlib. 
 *        When these functions are invoked, newlib will internally call the functions provided by osal_mem.c.
 * @version 0.1
 * @date 2025-09-14
 * 
 * @copyright Copyright (c) 2025
 * 
 */

#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include "./heap_trace/osal_mem.h"

//==================================================================================================
/**
 * @brief If used in a multi-threading environment, 
 *        please implement the following two functions to ensure thread safety. 
 *        Usually, this can be achieved through mutex locks or scheduling locks.
 */
void __malloc_lock(void)
{}
void __malloc_unlock(void)
{}

void *_malloc_r(struct _reent *ptr, size_t size)
{
    (void)ptr;
    void *p = OsalMemAlloc(size);
    if(NULL == p)
    {
        errno = ENOMEM;
    }
    return p;
}

void *_calloc_r(struct _reent *ptr, size_t count, size_t size)
{
    (void)ptr;
    void *p = OsalMemCalloc(count, size);
    if(NULL == p)
    {
        errno = ENOMEM;
    }
    return p;
}

void *_realloc_r(struct _reent *ptr, void *p, size_t size)
{
    (void)ptr;
    void *p2 = OsalMemRealloc(p, size);
    if(NULL == p2)
    {
        errno = ENOMEM;
    }
    return p2;
}

void *_memalign_r(struct _reent *ptr, size_t alignment, size_t size)
{
    (void)ptr;
    void *p = OsalAlignedMalloc(size, alignment);
    if(NULL == p)
    {
        errno = ENOMEM;
    }
    return p;
}

void _free_r(struct _reent *ptr, void *p)
{
    (void)ptr;
    OsalMemFree(p);
}
//==================================================================================================
size_t heap_total_free_min(void)
{
    return OsalMemGetMinFreeSize();
}

size_t heap_total_free(void)
{
    return OsalMemGetFreeSize();
}
//==============================================================================
/**
 * 按指定的字节对齐申请 MEMORY
 * 下面两个函数必须成对使用
 * aligned_malloc() 不会检查 alignment,
 * 调用者必须保证 alignment 为 2^n （1，2，4，8，16，32，64 ...）
*/
void* aligned_malloc(size_t alignment, size_t size)
{
    size = (size + alignment - 1) & (~(alignment - 1));
    return aligned_alloc(alignment, size);
}

void aligned_free(void *p)
{
    free(p);
}
//==================================================================================================
//end files
